﻿function resetCanvas(canvas, canvasDivContainer) {
    //clear the canvas by readjusting the width/height

    if (canvas.length > 0) {
        canvas[0].width = canvasDivContainer.width();
        canvas[0].height = canvasDivContainer.height();
    }
}

function drawLineBetweenElements(pairedElements, canvas, canvasDivContainer/*sourceElement, targetElement, canvas, canvasDivContainer*/) {
    resetCanvas(canvas, canvasDivContainer);
    //uses HTML5 <canvas> to draw line representing relationship
    //IE support with excanvas.js

    //draw from/to the centre, not the top left
    //don't use .position()
    //that will be relative to the parent div and not the page
    var context = canvas[0].getContext('2d');

    for (var i = 0; i < pairedElements.length; i++) {

        var sourceElement = pairedElements[i][0];
        var targetElement = pairedElements[i][1];

        var sourceX = sourceElement.offset().left + sourceElement.width() + 25;
        var sourceY = sourceElement.offset().top + sourceElement.height() / 2;

        var targetX = targetElement.offset().left - 15;
        var targetY = targetElement.offset().top + targetElement.height() / 2;

        //you need to draw relative to the canvas not the page
        var canvasOffsetX = canvas.offset().left;
        var canvasOffsetY = canvas.offset().top;
        
        //draw line
        context.beginPath();
        context.moveTo(Math.abs(sourceX - canvasOffsetX), Math.abs(sourceY - canvasOffsetY));
        context.lineTo(Math.abs(targetX - canvasOffsetX), Math.abs(targetY - canvasOffsetY));
        context.closePath();
        //ink line
        context.lineWidth = 2;
        context.strokeStyle = "#000"; //black
        context.stroke();
    }
}

function drawDummy(canvas, x, y) {
    var context = canvas[0].getContext('2d');
    context.beginPath();
    context.moveTo(0, 0);
    context.lineTo(x, y);
    context.closePath();
    //ink line
    context.lineWidth = 2;
    context.strokeStyle = "#000"; //black
    context.stroke();
}

